C	Copyright Eric Fuller, 2001-2007

	SUBROUTINE CALCCHI(CHISQ,NDAT,
     *  X1,X2,AFUNC1,AFUNC2,MA,PHI,A,
     *  Z1,Z2,Y1,Y2,SIG1,SIG2)

	INCLUDE 'pfit.cmn'



	REAL*8 CHISQ
	INTEGER*4 NDAT
	REAL*8 X1(NMAX),X2(NMAX),AFUNC1(MMAX),AFUNC2(MMAX)
	INTEGER*4 MA
	REAL*8 PHI,A(MMAX),Z1(NMAX),Z2(NMAX)
	REAL*8 Y1(NMAX),Y2(NMAX),SIG1(NMAX),SIG2(NMAX)

	REAL*8 SUM1,SUM2
	INTEGER*4 I,J

	EXTERNAL FUNCS



C	CALCULATE CHI SQUARED FOR THE CURRENT FIT PARAMETERS


	CHISQ=0.0

	DO I=1,NDAT

	  CALL FUNCS(X1(I),X2(I),AFUNC1,AFUNC2,MA,PHI)

	  SUM1=0.0
	  SUM2=0.0
	  DO J=1,MA
	    SUM1=SUM1+A(J)*AFUNC1(J)
	    SUM2=SUM2+A(J)*AFUNC2(J)
	    ENDDO
	  Z1(I)=SUM1
	  Z2(I)=SUM2

	  CHISQ=CHISQ +
     *      ((Y1(I)-Z1(I))/SIG1(I))**2 +
     *      ((Y2(I)-Z2(I))/SIG2(I))**2
	  ENDDO



	WRITE(*,50) CHISQ



50	FORMAT('Chi Squared       : ',F6.1)



	RETURN

	END




